from requests import request as http
from requests.utils import requote_uri
from typing import Dict, List
from collections import OrderedDict


class Kibana(object):
    def __init__(self, host: str = '127.0.0.1', schema: str = 'http', port: int = 5601, username: str = None,
                 password: str = None):
        self.host = host
        self.schema = schema
        self.port = port
        self.schema = schema
        self.username = username
        self.password = password

    def get_index_pattern(self):
        if self.username:
            r = http("GET", f'{self.schema}://{self.host}:{self.port}/api/saved_objects/_find?type=index-pattern',
                     auth=(self.username, self.password))
        else:
            r = http("GET", f'{self.schema}://{self.host}:{self.port}/api/saved_objects/_find?type=index-pattern')
        if r.status_code != 200:
            return '数据获取异常'
        return r.json()

    def get_index_pattern_ids(self) -> Dict:
        if self.username:
            r = http("GET", f'{self.schema}://{self.host}:{self.port}/api/saved_objects/_find?type=index-pattern',
                     auth=(self.username, self.password))
        else:
            r = http("GET", f'{self.schema}://{self.host}:{self.port}/api/saved_objects/_find?type=index-pattern')
        if r.status_code != 200:
            return {}
        data = {}
        for item in r.json().get('saved_objects'):
            data.update({item.get('attributes').get('title'): item.get('id')})
        return data

    def get_error_log_app_url(self, index_pattern_id: str, filter_fields_app, cst_begin_time: str, cst_end_time: str,
                              exclude_keywords: List):
        url = []
        # negate:!f (否定:false 过滤条件)
        kibana_url = f"{self.schema}://{self.host}:{self.port}/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'{cst_begin_time}',to:'{cst_end_time}'))&_a=(columns:!(_source),filters:!(('$state':(store:appState),"
        filter_level_error = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:level,negate:!f,params:(query:ERROR),type:phrase),query:(match_phrase:(level:ERROR))),('$state':(store:appState),"
        filter_fields_app = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:fields.app,negate:!f,params:(query:{filter_fields_app}),type:phrase),query:(match_phrase:(fields.app:{filter_fields_app}))),('$state':(store:appState),"
        url.append(kibana_url)
        url.append(filter_level_error)
        url.append(filter_fields_app)
        if exclude_keywords:
            quote_exclude_keywords = [requote_uri(item) for item in exclude_keywords]
            # negate:!t (否定:true 排查条件)
            for idx, exclude_keyword in enumerate(quote_exclude_keywords):
                # 最后一行拼接
                if idx == len(quote_exclude_keywords) - 1:
                    exclude_quote_message = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:message,negate:!t,params:(query:'{exclude_keyword}'),type:phrase),query:(match_phrase:(message:'{exclude_keyword}')))),index:'{index_pattern_id}',interval:auto,query:(language:lucene,query:''),sort:!())"
                    print(exclude_quote_message)
                    url.append(exclude_quote_message)
                else:
                    exclude_quote_message = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:message,negate:!t,params:(query:'{exclude_keyword}'),type:phrase),query:(match_phrase:(message:'{exclude_keyword}'))),('$state':(store:appState),"
                    url.append(exclude_quote_message)

        return ''.join(url)


if __name__ == '__main__':
    from pprint import pprint

    kibana = Kibana(host='kibana.wolaidai.com', schema='https', port=443)
    # kibana = Kibana(host='106.52.172.23', username='elastic', password='q5f2qNfUJQyvZPIz57MZ')
    pprint(kibana.get_index_pattern_ids())
    # pprint(requote_uri("Something Cool"))

    # kibana.get_error_log_app_url('34118c30-82a6-11ec-a335-a14a62acd312', 'thirdparty-sync', '2022-01-28T16:00:00.000Z',
    #                              '2022-01-29T16:00:00.000Z', ['java.lang.NullPointerException',
    #                                                           'com.welab.thirdparty.sync.exception.ThirdpartySyncException'])

# def index_pattern()
#
#
# def url_long_to_short(long_url, shout_url_api):
#     data = {'long_url': long_url}
#     res = requests.post(shout_url_api, data=data)
#     return res.text
#
#

# def kibana_url():
#     pass
#
# def kibana_url_old(params):
#     e_index = params['e_index']
#     shout_url_api = params['shout_url_api']
#     utc_begin_time = params['utc_begin_time']
#     utc_end_time = params['utc_end_time']
#     service = params['service']
#     exclude_keywords = params['exclude_keywords']
#
#     filters_level = f"('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'{e_index}',key:level,negate:!f,params:(query:error,type:phrase),type:phrase,value:error),query:(match:(level:(query:error,type:phrase))))"
#     filters_server_name = f"('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'{e_index}',key:fields.app,negate:!f,params:(query:{service},type:phrase),type:phrase,value:{service}),query:(match:(fields.app:(query:{service},type:phrase))))"
#
#     if exclude_keywords:
#         quote_exp_error_list = [parse.quote(item) for item in exclude_keywords.split(',')]
#         filters_message_meta_params = "!{}".format(str(tuple(quote_exp_error_list)).replace(' ', '')).replace(',)',
#                                                                                                               ')')
#         filters_message_meta_value = "'{}'".format(','.join(quote_exp_error_list))
#         filters_message_query_bool_should = "!("
#         for item in quote_exp_error_list:
#             filters_message_query_bool_should = filters_message_query_bool_should + f"(match_phrase:(message:'{item}')),"
#         filters_message_query_bool_should = filters_message_query_bool_should.rstrip(',') + ')'
#         filters_message = f",('$state':(store:appState),meta:(alias:!n,disabled:!f,index:fdcf5d60-a9f4-11e8-809c-57280b4ac664,key:message,negate:!t,params:{filters_message_meta_params},type:phrases,value:{filters_message_meta_value}),query:(bool:(minimum_should_match:1,should:{filters_message_query_bool_should})))"
#     else:
#         filters_message = ''
#
#     k_url_filters = f"filters:!({filters_level},{filters_server_name}{filters_message})"
#
#     k_url_g = f"_g=(refreshInterval:(pause:!t,value:0),time:(from:'{utc_begin_time}',mode:absolute,to:'{utc_end_time}'))"
#     k_url_a = f"_a=(columns:!(message),{k_url_filters},index:'{e_index}',interval:auto,query:(language:lucene,query:''),sort:!('@timestamp',desc))"
#
#     k_url = f"http://kibana.wolaidai.com/app/kibana#/discover?{k_url_g}&{k_url_a}"
#     k_url_link = f'<a href={k_url}>点击查看</a>'
# k_short_url = url_long_to_short(k_url, shout_url_api)
# if k_short_url:
#     res = k_short_url
# else:
#     res = k_url_link
# return k_url_link


# if __name__ == '__main__':
#     requote_uri("Something Cool")
